import { login, logout, getInfo } from "@/api/user";
import storage from "@/utils/storage";

const savedUser = storage.getSessionObject("loginUser");

const user = {
  state: {
    userName: savedUser?.ydlUser?.userName || "",
    nickName: savedUser?.ydlUser?.nickName || "",
    token: savedUser?.token || "",
    roles: [],
    permissions: [],
  },
  getters: {
    IS_LOGIN(state) {
      return state.userName != "" && state.token != "";
    },
    permissions(state) {
      return state.permissions;
    },
    roles(state) {
      return state.roles;
    },
  },
  mutations: {
    SAVE_USER(state, user) {
      state.userName = user.userName;
      state.nickName = user.nickName;
    },
    SAVE_TOKEN(state, token) {
      state.token = token;
    },
    SAVE_ROLES(state, roles) {
      state.roles = roles;
    },
    SAVE_PERMISSION(state, permissions) {
      state.permissions = permissions;
    },
  },
  actions: {
    LOGIN({ commit }, user) {
      return login(user).then((res) => {
        // 需要将获取的数据保存起来
        commit("SAVE_USER", res.data.ydlUser);
        commit("SAVE_TOKEN", res.data.token);
        storage.saveSessionObject("loginUser", res.data);
        return res;
      });
    },
    LOGOUT({ commit }) {
      return logout().then((res) => {
        commit("SAVE_USER", "");
        commit("SAVE_TOKEN", "");
        storage.remove("loginUser", res.data);
        return res;
      });
    },
    GET_INFO({ commit }) {
      return new Promise((resolve) => {
        getInfo().then((res) => {
          commit("SAVE_ROLES", res.data.roles);
          commit("SAVE_PERMISSION", res.data.perms);
          resolve();
        });
      });
    },
  },
};

export default user;
